//
//  VideoDetailViewController.swift
//  fsapp
//
//  Created by zguang on 17/7/27.
//  Copyright © 2017年 huangshengjie. All rights reserved.
//

import UIKit
import MobilePlayer
import Alamofire
import SVProgressHUD


class VideoDetailViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{
    
    var playStatus = false
    var player:MyPlayer!

    var footerRefreshView :FCXRefreshFooterView?
    let usd = UserSave()
    var page = 2
    var tableview : UITableView!
    var headerView1 = UIView()
    var s0title = ""
    var s0info = ""
    var buyStatus = "0"
    var s1Image = [String]()
    var s1title = [String]()
    var s1playTime = [String]()
    var s1playCount = [String]()
    var s2Image = [String]()
    var s2title = [String]()
    var s2content = [String]()
    var s2time =  [String]()
    var s1id = [String]()
    var s1url = [String]()
    
     let header1 = detailUI(1)
    var money = String()
    var time =  String()
    var playCout = String()
    var likeCount = String()
    var commitCount = String()
    var starCount = String()
    var cover = String()
    var videoId = String()
    var isClollected = ""
    var isLike = ""
    var refreshControl = UIRefreshControl()
    var videoURL = ""
    var playVC2 = MobilePlayerViewController(contentURL:NSURL(string:"") as! URL)
    //MARK: - 构造函数
    
    init(_ videpUrl:String,_ videoId:String) {
        SVProgressHUD.show(withStatus: "加载中")
        super.init(nibName: nil, bundle: nil)
        self.videoId = videoId
        self.videoURL = videpUrl
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.navigationBar.isHidden = true
        super.viewWillAppear(animated)
     //   if player == nil{
     //      self.playAction()
      //  }
       // let dict:NSDictionary = [NSForegroundColorAttributeName: UIColor.white,NSFontAttributeName : UIFont.boldSystemFont(ofSize: 18)]
        //标题颜色
       // self.navigationController?.navigationBar.titleTextAttributes = dict as? [String : AnyObject]
       // self.navigationItem.title = "视频播放"
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if player != nil{
        self.player.prepareToDealloc()
        }
       // SVProgressHUD.dismiss()
    }
    
//    deinit {
//        // 销毁播放器
//       if player != nil{
//            self.player.prepareToDealloc()
//        }
//        print("prepareToDealloc")
//    }
//    
    override func viewDidLoad() {
        
        
       
        super.viewDidLoad()
        
        refreshControl.addTarget(self, action: #selector(refresh),
                                 for: .valueChanged)
        refreshControl.attributedTitle = NSAttributedString(string: "下拉刷新数据")
       
    
        
        getCommit()
        getVideoDetail()
        getRelated()
       
        initTV()
         addRefreshView()
         tableview.addSubview(refreshControl)
      
       // refreshData()
       // tableview.bounces = false
       // tableview.contentInset = UIEdgeInsetsMake(0, 0, 10, 0)
        // self.tabBarController?.hidesBottomBarWhenPushed = true
        self.edgesForExtendedLayout = UIRectEdge(rawValue:0)
        //self.navigationItem.title = "视频播放"
       
        let item = UIBarButtonItem(image: #imageLiteral(resourceName: "分享"), style: .plain, target: self, action: #selector(touchShare))
        item.imageInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)
        self.navigationItem.rightBarButtonItem = item
        self.changeVideo.addTarget(self, action: #selector(getRelated), for: .touchUpInside)
        self.header1.commitInput.addTarget(self, action: #selector(textEdit), for: .touchUpInside)
        self.header1.closeButton.addTarget(self, action: #selector(closeComment), for: .touchUpInside)
        
        
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: #selector(returnKeyboard))
          header1.submitbackView.addGestureRecognizer(tap)
         header1.commentBackview.addGestureRecognizer(tap)
        //initVideo()
 

        
        // Do any additional setup after loading the view.
    }
    
  
    func returnKeyboard(){
      header1.commentView.resignFirstResponder()
    }
    
    func refresh(){
        self.page = 2
       // getVideoDetail()
        self.s2title.removeAll()
        self.s2time.removeAll()
        self.s2content.removeAll()
        self.s2Image.removeAll()
        getCommit()
       // getRelated()
        //self.tableview.reloadData()
    }
    
    func addRefreshView() {
        footerRefreshView =
            tableview.addFCXRefreshFooter { [weak self] (refreshHeader) in
                self?.loadMoreAction()
        }
    }
    
    func loadMoreAction() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) { [weak self] in
            guard let weakSelf = self,
                let footerRefreshView = self?.footerRefreshView else {
                    return
            }
            
            weakSelf.getCommit(page: weakSelf.page)
            
            // weakSelf.rows += 20
            // self?.tableview.reloadData()
        }
        
    }
    
    

    
    
    func touchShare(){
        //分享的标题
        
            
            let url = "http://dahan-api.heiyou.net/index.php/home/video/share"
            let paramdic = ["video_id":self.videoId]
           loadCookies()
            Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response
                in
                
                if let al = response.response{
                    
                }else{
                    let alert = UIAlertView(title: "网络连接失败", message: "请稍后重试", delegate: nil, cancelButtonTitle: "知道了")
                    alert.show()
                }
                
                //response serialization
                if let JSON2 = response.result.value {
                    let js = JSON(JSON2)
                    print(js)
                    if  js["status"] == 199{
                        let alert = UIAlertController(title:"提示",message:"您还未登录，请先登录",preferredStyle:.alert)
                        let cancel = UIAlertAction(title:"取消",style:.cancel,handler: nil)
                        let okActioin = UIAlertAction(
                            title:"登录",style:.default,handler:{
                                action in
                                
                                let nav = UINavigationController(rootViewController:LoginViewController())
                                self.present(nav, animated: true, completion: nil)
                                //self.navigationController?.pushViewController(LoginViewController(), animated: true)
                        }
                        )
                        
                        alert.addAction(cancel)
                        alert.addAction(okActioin)
                        self.present(alert, animated: true, completion: nil)

                    }
                    
                        if let url = js["result"]["pic_src"].string{
                          
                            let textToShare: String = "我发现了一个非常好用的易经学习软件，快来试试吧"
                            //分享的图片
                            let image = UIImageView()
                            image.imageFromURL(self.cover, placeholder: #imageLiteral(resourceName: "test"))
                            let imageToShare =  image.image
                            //分享的url
                            let urlToShare = "https://itunes.apple.com/us/app/%E5%A4%A7%E6%B1%89%E6%98%93%E7%BB%8F%E4%B9%A6%E9%99%A2%E6%99%BA%E6%85%A7%E7%94%9F%E6%B4%BB/id1266534282?l=zh&ls=1&mt=8"
                            //在这里呢 如果想分享图片 就把图片添加进去  文字什么的通上
                            var activityItems: [Any] = [textToShare,url]
                            let activityVC = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
                            //不出现在活动项目
                            activityVC.excludedActivityTypes = [UIActivityType.print, UIActivityType.copyToPasteboard, UIActivityType.assignToContact, UIActivityType.saveToCameraRoll]
                            self.present(activityVC, animated: true) { _ in }
                            // 分享之后的回调
                            activityVC.completionWithItemsHandler = {(_ activityType: UIActivityType?, _ completed: Bool, _ returnedItems: [Any]?, _ activityError: Error?) -> Void in
                                if completed {
                                    print("completed")
                                    //分享 成功
                                }
                                else {
                                    print("cancled")
                                    //分享 取消
                                }
                            }

                        }
                        
                    
                    
                }
            }
            
    

        
        
        
       
       //self.playVC2.showContentActions()
    }
    
    
    func textEdit(_ text:UITextField){
     // text.isEnabled = false
        header1.commentView.becomeFirstResponder()
      self.view.addSubview(header1.commentBackview)
      
    
    }
    
    func closeComment(){
       self.header1.commentBackview.removeFromSuperview()
    }
    
    
    
    //MARK: - 定制播放器
    func initVideo(){
   
        let fullScreenButton = UIButton()
        
        fullScreenButton.setBackgroundImage(#imageLiteral(resourceName: "分享"), for: .normal)
        fullScreenButton.addTarget(self, action: #selector(touchShare), for: .touchUpInside)
       self.headerView1.addSubview(fullScreenButton)
        //        self.player.addSubview(fullScreenButton)
        fullScreenButton.snp.makeConstraints{ (make) in
            make.top.equalTo(25)
            make.right.equalTo(-10)
            make.height.width.equalTo(20)
        }

      
        self.headerView1.frame = CGRect(x:0,y:0,width:SCREEN_WIDTH,height:height(558))
        //headerView1.addSubview(playVC2.view)
        
        header1.playButton.addTarget(self, action: #selector(playAction), for: .touchUpInside)
       
    
        header1.backImage.imageFromURL(cover, placeholder: #imageLiteral(resourceName: "test"))
        
        header1.timeSpan.text = time
        header1.timeSpan.font = UIFont.systemFont(ofSize: height(28))
        
        header1.money.text = "¥ " + money
       header1.videoCount.setTitle(playCout, for: .normal)
        header1.likeCount.setTitle(likeCount, for: .normal)
        header1.likeCount.tag = 0;
       
        header1.likeCount.addTarget(self, action: #selector(actionRequest(_:)), for: .touchUpInside)
        header1.starCount.tag = 1;
        header1.starCount.addTarget(self, action: #selector(actionRequest(_:)), for: .touchUpInside)
        header1.coommitCount.setTitle(commitCount, for: .normal)
        header1.starCount.setTitle(starCount, for: .normal)
        header1.submitButton.addTarget(self, action: #selector(actionComment), for: .touchUpInside)
        headerView1.addSubview(header1.cellBackView)
        self.returnButton.addTarget(self, action: #selector(backBtn), for: .touchUpInside)
        self.headerView1.addSubview(returnButton)
        self.view.addSubview(headerView1)
    }
    
    func judgeBuy()->Bool{
        


  
        
        var status = false
        if self.buyStatus == "0"{
        let alertController = UIAlertController(title: "尚未购买此视频",
                                                message: "点击确认即从余额扣除相应金额", preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let okAction = UIAlertAction(title: "好的", style: .default, handler: {
            action in
            
            
            let url =  "http://dahan-api.heiyou.net/index.php/home/index/buyVideo"
            var paramdic = ["video_id":self.videoId]
            
            loadCookies()
            Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response
                in
                
                if let al = response.response{
                    
                }else{
                    SVProgressHUD.showError(withStatus: "网络连接失败")
                }
                
                //response serialization
                if let JSON2 = response.result.value {
                    let js = JSON(JSON2)
                    print(js)
                    
                    if js["status"] == 200{
                        status = true
                        SVProgressHUD.showSuccess(withStatus: js["msg"].string!)
                        self.buyStatus = "1"
                        SVProgressHUD.dismiss(withDelay: 2)
                        self.tableview?.reloadData()
                    }else{
                       // SVProgressHUD.showError(withStatus: js["msg"].string!)
                        if  js["status"] == 199{
                            
                            
                            
                            let alertController = UIAlertController(title: "提示",
                                                                    message: "您尚未登录", preferredStyle: .alert)
                            let cancelAction = UIAlertAction(title: "取消观看", style: .cancel, handler: nil)
                            let okAction = UIAlertAction(title: "以普通用户登录（推荐）", style: .default, handler: {
                                action in
                                
                                let nav = UINavigationController(rootViewController:LoginViewController())
                                self.present(nav, animated: true, completion: nil)
                                
                            })
                            let okAction2 = UIAlertAction(title: "以游客身份登录（仅可在本机购买）", style: .default, handler: {
                                action in
                             
                                self.TAlarequest()
                                 //let nav = LoadViewController()
                                //nav.Alarequest()
                                
                                //print("点击了确定2")
                            })
                            alertController.addAction(cancelAction)
                            alertController.addAction(okAction)
                            alertController.addAction(okAction2)
                            self.present(alertController, animated: true, completion: nil)
                            
                            
                          

                        }
                        
                        if  js["status"] == 2005{
                            SVProgressHUD.dismiss(withDelay: 2)
                            SVProgressHUD.showError(withStatus: js["msg"].string!)
                            let vc = WalletViewController()
                            //vc.clickWalletViewBtn(rechargeBtn)
                            self.present(vc, animated: true, completion: nil)
                        }
                        
                        if js["status"] == 2006 {
                              SVProgressHUD.showSuccess(withStatus: js["msg"].string!)
                              self.buyStatus = "1"
                              self.tableview.reloadData()
                        }
                        
                        
                    }
                    
                }
            }

           // actionRequest(okAction)
            print("购买")
            
            
        })
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
        }else{
          return true
        }
        return status
    }
    
    
 
    
    func playAction(){
        
//        if !usd.readSex(){
//            let nav = UINavigationController(rootViewController:SetNameViewController())
//            self.present(nav, animated: true)
//        }
        
        
        
        //self.navigationController?.navigationBar.isHidden = false
       
//        if !usd.readLogin(){
//            let alert = UIAlertController(title:"提示",message:"您还未登录，请先登录",preferredStyle:.alert)
//            let cancel = UIAlertAction(title:"取消",style:.cancel,handler: nil)
//            let okActioin = UIAlertAction(
//                title:"登录",style:.default,handler:{
//                    action in
//                    let nav = UINavigationController(rootViewController:LoginViewController())
//                    self.present(nav, animated: true, completion: nil)
//                    // self.navigationController?.pushViewController(LoginViewController(), animated: true)
//            }
//            )
//            
//            alert.addAction(cancel)
//            alert.addAction(okActioin)
//            self.present(alert, animated: true, completion: nil)
//            return;
//          //self.buyStatus = "0"
//        }
        if usd.readVip(){
            self.buyStatus = "1"
        }
        
        
        if judgeBuy(){
        
      //  self.tabBarController?.tabBar.frame = CGRect.zero
        self.player =  MyPlayer(frame: CGRect.zero, urlString: self.videoURL, title: "    "  + self.s0title)
        self.player.contrainerViewController = self
        self.view.addSubview(player)
        self.playStatus = true
            
        self.headerView1.transform = CGAffineTransform(translationX: 0, y: 10)
       // self.tableview.reloadData()
       //self.tableview.headerView(forSection: 0)?.removeFromSuperview()
        let fullScreenButton = UIButton()
        
            fullScreenButton.setBackgroundImage(#imageLiteral(resourceName: "分享"), for: .normal)
            fullScreenButton.addTarget(self, action: #selector(touchShare), for: .touchUpInside)
        self.player.addSubview(fullScreenButton)
        fullScreenButton.snp.makeConstraints{ (make) in
                make.top.equalTo(25)
                make.right.equalTo(-10)
                make.height.width.equalTo(20)
            }
      //  fullScreenButton.imageEdgeInsets = UIEdgeInsets.init(top:10, left: 0, bottom: 0, right: 10)
            
        player.snp.makeConstraints { (make) in
                make.top.equalTo(view.snp.top)
                make.left.equalTo(view.snp.left)
                make.right.equalTo(view.snp.right)
                make.height.equalTo(view.snp.width).multipliedBy(9.0/16.0)
            }
            
            let qe: DispatchQoS = DispatchQoS(qosClass: .default, relativePriority: 0)
            DispatchQueue.global(qos: qe.qosClass).async {
                
            }
            
            
      /*
        let boudle = Bundle.main
        let config = MobilePlayerConfig(fileURL: boudle.url(forResource: "myplayer", withExtension: "json")!)
        playVC2.title = "\(title)"
        playVC2 = MobilePlayerViewController(contentURL: (videoURL as! URL),config:config)
        // playVC2.showOverlayViewController(<#T##overlayViewController: MobilePlayerOverlayViewController##MobilePlayerOverlayViewController#>)
        
        playVC2.view.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: height(402))
        let fullScreenButton = UIButton(frame: CGRect(x: playVC2.view.frame.width - 45, y: playVC2.view.frame.height - 35, width: 30, height: 30))
        fullScreenButton.setBackgroundImage(#imageLiteral(resourceName: "主页方框"), for: .normal)
        playVC2.view.addSubview(fullScreenButton)
        fullScreenButton.addTarget(self, action: #selector(touch), for: .touchUpInside)
        //fullScreenButton.addTarget(self, action: #selector(touch), for: .tou)
        playVC2.activityItems = [videoURL!]

      self.headerView1.addSubview(playVC2.view)
      playVC2.play()
       */
        }
    
    }
    
    
    func touch(_ btn:UIButton){
        
        btn.isHidden = true
        let boudle = Bundle.main
        let config = MobilePlayerConfig(fileURL: boudle.url(forResource: "myplayer2", withExtension: "json")!)
        let playerVC = MobilePlayerViewController(contentURL: videoURL as! URL,config:config)
        playerVC.title = self.s0title
        playerVC.activityItems = [videoURL]
      //  playerVC.viewWillDisappear()
       presentMoviePlayerViewControllerAnimated(playerVC)
  
        if (self.playVC2.isBeingDismissed) != nil{
            btn.isHidden = false
        }
      
        
        // self.present(_2ViewController(), animated: true, completion: nil)
        // presentMoviePlayerViewControllerAnimated(playVC2)
        
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    
    // MARK: - tableview协议
    
    func initTV (){
        
        
       // tableview.bounces = false
      //  self.edgesForExtendedLayout = UIRectEdge(rawValue:0)
     //   tableview?.frame =
     // tableview.bounces = false
     //   if let bottom = (self.tabBarController?.tabBar.frame.height){
        
        self.view.backgroundColor = backColor
           let fr =  CGRect(x:0,y:height(558),width:SCREEN_WIDTH,height:SCREEN_HEIGHT - height(558))
        
        tableview = UITableView(frame: fr ,style: .grouped)
       // tableview.bounces = false
        tableview?.delegate = self
        tableview?.dataSource = self
        tableview?.backgroundColor = backColor
   
        // view.backgroundColor = UIColor.red
        // self.view.addSubview(tableview)
        self.view.addSubview(tableview)
        
    }
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.header1.commitInput.resignFirstResponder()
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return height(10)
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 1
        case 1:
            return s1title.count
        default:
            return s2title.count
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 0{
         //tableview.rowHeight = UITableViewAutomaticDimension
           return height(162)
        }else if indexPath.section == 1{
           return height(183)
        }else{
          return  height(156)
        }
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0{
        let cell = UITableViewCell(style:.subtitle,reuseIdentifier:"cell")
        cell.textLabel?.text = s0title
        cell.textLabel?.font = UIFont.boldSystemFont(ofSize: height(32))
        cell.detailTextLabel?.numberOfLines = 0
        cell.detailTextLabel?.font = UIFont.systemFont(ofSize: height(26))
        cell.detailTextLabel?.textColor = title2color
        
        cell.detailTextLabel?.text = s0info
        return cell
        }else if indexPath.section == 1 {
            let cell = RelatedTableViewCell(style:.subtitle,reuseIdentifier:"cell");

            cell.leftImage.imageFromURL(s1Image[indexPath.row], placeholder: #imageLiteral(resourceName: "test"))
                cell.title.text = s1title[indexPath.row]
                cell.playTime.text = "时长： " + s1playTime[indexPath.row]
            cell.playCount.text = "播放量：" + s1playCount[indexPath.row]
            //cell.title.sizeToFit()
            //cell.title.lineBreakMode = .
            cell.title.numberOfLines = 0
            cell.playCount.sizeToFit()
            cell.playTime.sizeToFit()
            
            return cell
        }else{
                let cell = CommitTableViewCell(style:.subtitle,reuseIdentifier:"cell")
                // cell.leftImage =
            cell.title.text = self.s2title[indexPath.row]
            cell.title.sizeToFit()
            cell.leftImage.imageFromURL(self.s2Image[indexPath.row], placeholder: #imageLiteral(resourceName: "test"))
            
            cell.content.text = s2content[indexPath.row]
            cell.sendTime.text = s2time[indexPath.row]
            cell.content.numberOfLines = 0
            cell.sendTime.sizeToFit()
            return cell
        }
     
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 1{
       self.initVideo()
      // self.navigationController?.popToRootViewController(animated: false)
       //     self.player.
        //self.player.prepareToDealloc()
           // if self.player != nil{
           //self.player.changePlay(palyUrl:self.s1url[indexPath.row] , title: self.s1id[indexPath.row])
            //}
           let newVc = VideoDetailViewController(self.s1url[indexPath.row],self.s1id[indexPath.row])
          self.present(newVc, animated: true, completion: nil)
          //self.navigationController?.pushViewController(newVc, animated: true)
            if player != nil {
            self.player.removeFromSuperview()
            }
        }
        
    }
    
   
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0:
           
            return height(0)
            
        default:
            return height(83)
        }
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case 0:
            initVideo()
            return headerView1
            
        case 1:
            section1backview.addSubview(changeVideo)
            return section1backview
        default:
            return section2backview
        }
        
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
       // if section == 2 {
       //    return footerReload
      //}
        
        return nil
        
    }

    
    func sscrollViewDidScroll(_ scrollView: UIScrollView) {
        //组头高度
        let sectionHeaderHeight:CGFloat = 64
        //获取是否有默认调整的内边距
        let defaultEdgeTop:CGFloat = navigationController?.navigationBar != nil
            &&
            self.automaticallyAdjustsScrollViewInsets ? 64 : 0
        
        if scrollView.contentOffset.y >= -defaultEdgeTop &&
            scrollView.contentOffset.y <= sectionHeaderHeight - defaultEdgeTop  {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0)
        }
        else if (scrollView.contentOffset.y>=sectionHeaderHeight - defaultEdgeTop) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight + defaultEdgeTop,
                                                       0, 0, 0)
        }
    }
    // MARK: - 网络请求
    
    
 
    
    var limit = 1;
    func getRelated(){
        let url = "http://dahan-api.heiyou.net/index.php/home/video/getVideoInfo"
        let paramdic = ["video_id":self.videoId]
        Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response in
            
            if let al = response.response{
                
            }else{
                let alert = UIAlertView(title: "网络连接失败", message: "请稍后重试", delegate: nil, cancelButtonTitle: "知道了")
                alert.show()
                self.dismiss(animated: true, completion: nil)
            }
            
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
                //print(js)
                if js["status"] == 200{
                if !self.s1title.isEmpty {
                    self.s1Image.removeAll()
                    self.s1title.removeAll()
                    self.s1id.removeAll()
                    self.s1playTime.removeAll()
                    self.s1playCount.removeAll()
                    self.s1url.removeAll()
                }
                    if js["result"].count != 0{
                        for i in 0...js["result"].count-1{
                            self.s1Image.append(js["result"][i]["pic_src"].string!)
                            self.s1title.append(js["result"][i]["name"].string!)
                            if let long = js["result"][i]["duration"].string{
                                self.s1playTime.append(long)
                            }else{
                                self.s1playTime.append("0")
                            }
                            
                           self.s1playCount.append(js["result"][i]["play"].string!)
                            self.s1id.append(js["result"][i]["id"].string!)
                            self.s1url.append(js["result"][i]["video_src"].string!)
                            }
                
                      //print("请求次数" + "\(self.limit)")
                        self.tableview.reloadData()
                    }
                    
                
                }else if js["status"] == 3012{
                    if  self.self.limit < 16 {
                        self.getRelated()
                        self.limit += 1;
                    }
                }
                
            }
        }


    }
    
    func getCommit(){
        
    
    
        let url = "http://dahan-api.heiyou.net/index.php/home/video/getComment"
        let paramdic = ["video_id":self.videoId,"page":"1","limit":"10"]
        Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response
            in
            
            if let al = response.response{
              
            }else{
                let alert = UIAlertView(title: "网络连接失败", message: "请稍后重试", delegate: nil, cancelButtonTitle: "知道了")
                alert.show()
            }
            
          //response serialization
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
              //  print(js)
                if js["status"] == 200{
                    if js["result"].count != 0{
                        for i in 0...js["result"].count-1{
                            
                            self.s2time.append(js["result"][i]["time"].string!)
                            self.s2content.append(js["result"][i]["comment"].string!)
                            if let name = js["result"][i]["user_info"]["name"].string{
                            self.s2title.append(name)
                            }else{
                            self.s2title.append(" ")
                            }
                            if let name = js["result"][i]["user_info"]["img"].string{
                                self.s2Image.append(name)
                            }else{
                                self.s2Image.append("")
                            }
                         
                        }
                        
                       // var indexSet = IndexSet.init(integer: 1)
                       // self.tableview.reloadSections(indexSet, with: .automatic)

                        self.tableview.reloadSections(IndexSet(integersIn: 2...2), with: UITableViewRowAnimation.top)

                        //self.tableview.reloadData()
                        print(self.s2title.count)

                        self.refreshControl.endRefreshing()
                    }
                    
                }
                
            }
        }
    
    
    }
    
    
    func getCommit(page:Int){
        
        
        
        let url = "http://dahan-api.heiyou.net/index.php/home/video/getComment"
        let paramdic = ["video_id":self.videoId,"page":"\(page)","limit":"10"]
        Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response
            in
            
            if let al = response.response{
                
            }else{
                let alert = UIAlertView(title: "网络连接失败", message: "请稍后重试", delegate: nil, cancelButtonTitle: "知道了")
                alert.show()
            }
            
            //response serialization
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
                  print(js)
                if js["status"] == 200{
                    self.page += 1
                    if js["result"].count != 0{
                       /*
                        for i in 0...js["result"].count-1{
                            
                            self.s2time.append(js["result"][i]["time"].string!)
                            self.s2content.append(js["result"][i]["comment"].string!)
                            if let name = js["result"][i]["user_info"]["name"].string{
                                self.s2title.append(name)
                            }else{
                                self.s2title.append(" ")
                            }
                            if let name = js["result"][i]["user_info"]["img"].string{
                                self.s2Image.append(name)
                            }else{
                                self.s2Image.append("")
                            }
                            
                        }
                        
                        // var indexSet = IndexSet.init(integer: 1)
                        // self.tableview.reloadSections(indexSet, with: .automatic)
                        
                        self.tableview.reloadSections(IndexSet(integersIn: 2...2), with: UITableViewRowAnimation.top)
                        
                        //self.tableview.reloadData()
                        print(self.s2title.count)
                     */
                          self.refreshControl.endRefreshing()
                       self.footerRefreshView?.showNoMoreData();
                        //self.footerRefreshView?.endRefresh()
                    
                   }else{
                        self.footerRefreshView?.showNoMoreData();
                    }
                    
                }else{
                      self.footerRefreshView?.showNoMoreData();
                }
                
            }
        }
        
        
    }
    
    func getVideoDetail(){
        SVProgressHUD.show(withStatus: "loading")
        let url = "http://dahan-api.heiyou.net/index.php/home/video/videoDetail"
        let paramdic = ["video_id":self.videoId]
        Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response in
            
            if let al = response.response{
                print(al)
            }else{
                let alert = UIAlertView(title: "网络连接失败", message: "请稍后重试", delegate: nil, cancelButtonTitle: "知道了")
                alert.show()
            }
            
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
                 print(js)
    
                var newmoney = ""
                var newtime =  ""
                var newplayCout = ""
                var newlikeCount = String()
                var newcommitCount = String()
                var newstarCount = ""
                var newpic_src = String()
                var newtitle = String()
                var newInfo = String()
                var newcover = String()
                if(js["status"] == 200)
                {
                    print(js["result"]["actionPoint"],js["result"]["actionCollection"])
                    if let like =  js["result"]["actionPoint"].string{
                        self.isLike =  like
                        
                    }
                    if let collected =  js["result"]["actionCollection"].string{
                        self.isClollected =  collected
                    }
                    if let buy = js["result"]["actionBuy"].string{
                          self.buyStatus = buy
                    }else{
                          self.buyStatus = "0"
                    }
                newmoney = js["result"]["price"].string!
                newcover = js["result"]["pic_src"].string!
                newtitle = js["result"]["name"].string!
                newInfo = js["result"]["intro"].string!
                newplayCout = js["result"]["play"].string!
                newlikeCount = js["result"]["good"].string!
                if let ss =  js["result"]["nums"].string{
                   newstarCount = ss
                }
                newcommitCount = js["result"]["comment"].string!
                if let cc = js["result"]["duration"].string{
                  newtime = cc
                }
                    
                    self.s0title = newtitle
                    self.s0info = newInfo
                    self.time = newtime
                    self.money = newmoney
                    self.cover = newcover
                    self.likeCount = newlikeCount
                    self.commitCount = newcommitCount
                    self.starCount = newstarCount
                    self.playCout = newplayCout
                    
                    DispatchQueue.main.async {
                        if self.player == nil {
                           self.initVideo()
                        }else{
                           self.header1.likeCount.setTitle(self.likeCount, for: .normal)
                            self.header1.starCount.setTitle(self.starCount, for: .normal)
                        }
                    SVProgressHUD.dismiss()
                        if self.isLike == "1"{
                            self.header1.likeCount.isSelected = true
                        }
                        if self.isClollected == "1" {
                            self.header1.starCount.isSelected = true
                        }
                    self.tableview.reloadData()
                    }
                }
                else if js["status"] == 3017 {
                    
                    self.usd.deleteInfo()
                    let alertController = UIAlertController(title: "提示",
                                                            message: "您尚未登录", preferredStyle: .alert)
                    let cancelAction = UIAlertAction(title: "取消观看", style: .cancel, handler:{
                        action in
                        self.dismiss(animated: true, completion: nil)
                        SVProgressHUD.dismiss()
                    })
                    let okAction = UIAlertAction(title: "以普通用户登录（推荐）", style: .default, handler: {
                        action in
                        
                        let nav = UINavigationController(rootViewController:LoginViewController())
                        self.present(nav, animated: true, completion: nil)
                        
                    })
                    let okAction2 = UIAlertAction(title: "以游客身份登录（仅可在本机购买）", style: .default, handler: {
                        action in
                        
                        self.TAlarequest()
                        //let nav = LoadViewController()
                        //nav.Alarequest()
                        
                        //print("点击了确定2")
                    })
                    alertController.addAction(cancelAction)
                    alertController.addAction(okAction)
                    alertController.addAction(okAction2)
                    self.present(alertController, animated: true, completion: nil)
                    
                }
                
                else{
                    if let title = js["msg"].string{
                    let alert = UIAlertView(title: title, message: "请重试", delegate: nil, cancelButtonTitle: "知道了")
                    alert.show()
                    }
                    
                }
            }
                
                
            }
            
        }

    
    
    func actionComment(){
        
        /*判断登录
        if !self.usd.readId(){
            let alert = UIAlertController(title:"提示",message:"您还未登录，请先登录",preferredStyle:.alert)
            let cancel = UIAlertAction(title:"取消",style:.cancel,handler: nil)
            let okActioin = UIAlertAction(
                title:"登录",style:.default,handler:{
                    action in
                    let nav = UINavigationController(rootViewController:LoginViewController())
                    self.present(nav, animated: true, completion: nil)
            }
            )
            
            alert.addAction(cancel)
            alert.addAction(okActioin)
            self.present(alert, animated: true, completion: nil)
        }
      */
        
        let url = "http://dahan-api.heiyou.net/index.php/home/video/Comment"
        let comment:String = self.header1.commentView.text!
        if comment == ""{
           SVProgressHUD.showError(withStatus: "请输入内容")
           SVProgressHUD.dismiss(withDelay: 0.5)
            return
        
        }
        
        var paramdic = ["video_id":self.videoId,"comment":comment]
        
        loadCookies()
        Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response
            in
            
            if let al = response.response{
                
            }else{
                SVProgressHUD.showError(withStatus: "网络连接失败")
            }
            
            
            self.closeComment()
            self.header1.commentView.text = ""
            //response serialization
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
                print(js)
                if js["status"] == 200{
                    SVProgressHUD.dismiss(withDelay: 1, completion: nil)
                    SVProgressHUD.showSuccess(withStatus: js["msg"].string!)
                    self.refresh()
                }else{
                    
                    if  js["status"] == 199{
                        
                        let alert = UIAlertController(title:"提示",message:"您还未登录，请先登录",preferredStyle:.alert)
                        let cancel = UIAlertAction(title:"取消",style:.cancel,handler: nil)
                        let okActioin = UIAlertAction(
                            title:"登录",style:.default,handler:{
                           action in
                                let nav = UINavigationController(rootViewController:LoginViewController())
                                self.present(nav, animated: true, completion: nil)
                        // self.navigationController?.pushViewController(LoginViewController(), animated: true)
                        }
                        )
                        
                        alert.addAction(cancel)
                        alert.addAction(okActioin)
                        self.present(alert, animated: true, completion: nil)
                        
                        
                    }else{
                    
                       SVProgressHUD.showError(withStatus: js["msg"].string!)
                    }
                }
                
            }
        }
        
    }
    func actionRequest(_ action:UIButton){
        
        
        /*判断登录
        if !self.usd.readId(){
            let alert = UIAlertController(title:"提示",message:"您还未登录，请先登录",preferredStyle:.alert)
            let cancel = UIAlertAction(title:"取消",style:.cancel,handler: nil)
            let okActioin = UIAlertAction(
                title:"登录",style:.default,handler:{
                    action in
                    let nav = UINavigationController(rootViewController:LoginViewController())
                    self.present(nav, animated: true, completion: nil)
                
            }
            )
            
            alert.addAction(cancel)
            alert.addAction(okActioin)
            self.present(alert, animated: true, completion: nil)
            return
        }
        */
        
        var actionString = ""
        switch action.tag {
        case 0:
            actionString = "Like"
        case 1:
            actionString = "collections"
        default:
            actionString = ""
        }
        
        
        let url = "http://dahan-api.heiyou.net/index.php/home/video/" + actionString
        var paramdic = ["video_id":self.videoId]
        
        loadCookies()
        Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response
            in
            
            if let al = response.response{
                
            }else{
                SVProgressHUD.showError(withStatus: "网络连接失败")
            }
            
            //response serialization
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
                print(js)
                if js["status"] == 200{
                   action.isSelected = !action.isSelected
                    //SVProgressHUD.showSuccess(withStatus: js["msg"].string!)
                    //SVProgressHUD.dismiss(withDelay: 1, completion: nil)
                   self.getVideoDetail()
                
                }else{
                    
                 if  js["status"] == 199{
                    let alert = UIAlertController(title:"提示",message:"您还未登录，请先登录",preferredStyle:.alert)
                    let cancel = UIAlertAction(title:"取消",style:.cancel,handler: nil)
                    let okActioin = UIAlertAction(
                        title:"登录",style:.default,handler:{
                            action in
                            let nav = UINavigationController(rootViewController:LoginViewController())
                            self.present(nav, animated: true, completion: nil)
                            //self.navigationController?.pushViewController(LoginViewController(), animated: true)
                    }
                    )
                    
                    alert.addAction(cancel)
                    alert.addAction(okActioin)
                    self.present(alert, animated: true, completion: nil)
                
                 }else {
                    
                     SVProgressHUD.showError(withStatus: js["msg"].string!);
                    }
                }
                
            }
        }
    
    }
    
  // MARK: - 游客登录
    var sessionID = String()
    var ussd = UserSave()
    func TAlarequest(){
        //let account:String = self.loginview.phoneText.text!;
        //let password:String = self.loginview.passwordText.text!
        let url = "http://dahan-api.heiyou.net/index.php/home/user/visitorLogin"
        let paramdic =
            ["udid":String(describing: idfa)]
        
        Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response in
            print("result=========================")
            if let sds = response.response{
                
            }else{
                print("网络异常")
            }
            // print(response.response?.allHeaderFields)
            
            
            if let cookies =  HTTPCookieStorage.shared.cookies{
                print(cookies)
                self.saveCookies(response: response)
                //          let usr = UserDefaults.standard
                //  usr.set(cookies as [String:String], forKey: "savedCookies")
                //  UserDefaults.standard.synchronize()
                print(cookies)
                for cookie in cookies{
                    self.sessionID = String(cookie.name)+("=") + String(cookie.value)
                }
                
                
                //存储用户Cookie
                
                let userDefault = UserDefaults.standard
                userDefault.set(self.sessionID, forKey: "Cookie")
                print(self.sessionID)
                
            }else {
                print("登录出错,未获取到sessionID")
                return
            }
            
            if self.sessionID == "" {
                print("登录出错,未获取到sessionID")
                //return
            }
            
            
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
                print(js)
                DispatchQueue.main.async {
                    if(js["status"]==200){
                        
                        SVProgressHUD.showSuccess(withStatus: "游客登录成功")
                        
                        //       print(self.jsonjson(aa: response.result.value))
                        //let usd = UserDefaults()
                        self.ussd.deleteInfo()
                        //self.ussd.saveInfo("1","18850076841", "1","0", "1","1","1","1","1", "1",sessionID: self.sessionID)
                        
                        if let name = js["result"]["name"].string{
                            if let img = js["result"]["img"].string{
                                if let sex = js["result"]["sex"].string{
                                    print(name)
                                    self.ussd.saveInfo("1", "18850076841", "", "", name,sex, img, "", "", "", sessionID: self.sessionID)
                                }else{
                                    self.ussd.saveInfo("1", "18850076841", "", "", name, "", img, "", "", "", sessionID: self.sessionID)
                                }
                            }
                            
                        }else{
                            print("获取个人信息失败")
                        }
                     }
                        print(self.ussd.readInfo())
                        
                        
                        
                    }
                    
                }}
            
            // print(account+password)
        }
    
    
    
    func saveCookies(response: DataResponse<Any>) {
        let headerFields = response.response?.allHeaderFields as! [String: String]
        let url = response.response?.url
        //let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url!)
        if let cookies =  HTTPCookieStorage.shared.cookies{
            var cookieArray = [[HTTPCookiePropertyKey: Any]]()
            for cookie in cookies {
                cookieArray.append(cookie.properties!)
            }
            UserDefaults.standard.set(cookieArray, forKey: "savedCookies")

            UserDefaults.standard.synchronize()
            
            print(UserDefaults.standard.array(forKey: "savedCookies")!)

           // print(String(describing: cookieArray))
        }
    }

    

    
    
    
  
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    
    
    // MARK: - SECTION2 VIEW
    
    
    lazy var returnButton:UIButton = {
        let btn = UIImageView()
        //imgV.frame = CGRectMake(WIDTH(23), HEIGHT(62), WIDTH(25), HEIGHT(45));
        
        btn.frame = CGRect(x: getWidth(width: 24), y: CGFloat(getHeight(62)), width: getWidth(width: 25), height: getHeight(45));
        btn.image = UIImage(named:"return")
        let back = UIButton()
        back.frame = CGRect(x: getWidth(width: 0), y: CGFloat(getHeight(0)), width: getWidth(width: 70), height: getHeight(128));
        back.addSubview(btn)
        return back
    }()
    
    
    func touchMore(_ btn:UIButton){
        self.refresh()
        btn.setTitle("没有更多了", for: .selected)
        btn.isSelected = true
        
    }
    
    func backBtn(){
        //self.navigationController?.navigationBar.isHidden = false
        self.dismiss(animated: true, completion: nil)
        self.navigationController?.popViewController(animated: true)
    
    }
    
    lazy var section1backview:UIView = {
        let view = UIView(frame:CGRect(x:0,y:0,width:SCREEN_WIDTH,height:height(82)))
        view.backgroundColor = UIColor.white
        let connectViedolabel = UILabel(frame:CGRect(x:width(20),y:height(26),width:0,height:0))
        connectViedolabel.text = "相关视频"
        connectViedolabel.font = UIFont.systemFont(ofSize: height(32))
        connectViedolabel.sizeToFit()
        view.addSubview(connectViedolabel)
        view.layer.borderWidth = height(1)
        view.layer.borderColor = lineColor.cgColor
        return view
    }()
    
    lazy var section2backview:UIView = {
        let view = UIView(frame:CGRect(x:0,y:0,width:SCREEN_WIDTH,height:height(82)))
        view.backgroundColor = UIColor.white
        let connectViedolabel = UILabel(frame:CGRect(x:width(20),y:height(26),width:0,height:0))
        connectViedolabel.text = "评论"
        connectViedolabel.font = UIFont.systemFont(ofSize: height(32))
        connectViedolabel.sizeToFit()
        view.addSubview(connectViedolabel)
        view.layer.borderWidth = height(1)
        view.layer.borderColor = lineColor.cgColor
        return view
    }()
    
    lazy var changeVideo:UIButton = {
        let button = UIButton()
        button.frame = CGRect(x:SCREEN_WIDTH-width(25+87),y:height(82/2-14),width:getWidth(width:120),height:height(28))
        button.titleLabel?.font = UIFont.systemFont(ofSize: height(28))
        button.setTitle("换一批", for: .normal)
        button.setTitleColor(naviColor, for: .normal)
        return button
    }()
    
    lazy var footerReload:UIView = {
        let view = UIView(frame:CGRect(x:0,y:0,width:SCREEN_WIDTH,height:height(82)))
        //view.backgroundColor = UIColor.white
        let button = UIButton()
        button.frame = CGRect(x:SCREEN_WIDTH/2-width(110),y:height(82/2-24),width:getWidth(width:220),height:height(28))
        button.titleLabel?.font = UIFont.systemFont(ofSize: height(28))
        button.setTitle("点击加载更多", for: .normal)
        button.addTarget(self, action: #selector(touchMore(_:)), for: .touchUpInside)
            
            button.setTitleColor(naviColor, for: .normal)

        view.layer.borderWidth = height(1)
        view.layer.borderColor = lineColor.cgColor
        view.addSubview(button)
        return view

    
    }()

}
extension UIColor {
    
    
    class func colorWith(redColor red: Int, green: Int, blue: Int, alpha: CGFloat) -> UIColor {
        let color = UIColor(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alpha)
        return color
    }
    
    
    
    
}
